import numpy as np


class EarlyStopping:
    def __init__(self, patience, min_delta, verbose):
        """
        Args:
            patience (int): 计数器。当loss没有改善时，将等待多少个epoch。
            min_delta (float): 为了被视为“改善”，最小的loss变化量。
            verbose (bool): 是否打印信息。
        """
        self.patience = patience
        self.min_delta = min_delta
        self.verbose = verbose
        self.counter = 0
        self.best_score = None
        self.early_stop = False
        self.val_loss_min = np.inf

    def __call__(self, val_loss, model):
        score = -val_loss

        if self.best_score is None:
            self.best_score = score
        elif score < self.best_score + self.min_delta:
            self.counter += 1
            if self.verbose:
                print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            if self.counter >= self.patience:
                self.early_stop = True
        else:
            self.best_score = score
            self.counter = 0

    def stop(self):
        return self.early_stop
